﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using SHFK.B2C.YouZanYun.Network;
using SHKF.B2C.BLL;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.BLL.SugarIOC;
using SHKF.B2C.BLL.WorkingCenter;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Entity.WorkingCenter;
using SHKF.B2C.Model.View.Center;
using SHKF.B2C.MQBase;
using SHKF.B2C.MQBase.Model.Order;
using SHKF.B2C.YouZanYun.Model.Inter.UpdateBranch;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks; 

namespace SHKF.B2C.YouZanYun.Consumer
{
    public class UpdateStockHostedService : BackgroundService
    {
        private readonly RabbitMqCore mQ;
        private readonly HttpClientYouZanYun httpClientYouZanYun;
        private readonly ProductInfoBLL productInfoBLL;
        private readonly WorkingCenterBLL workingCenterBLL;
        private readonly ShopMapBLL shopMapBLL;
        private readonly WareHouseDataWarehousBLL wareHouseDataWarehousBLL;  //分店分库存
        private readonly WareHouseDataAllBLL wareHouseDataAll;               //分店总库存
        private readonly ILogger<UpdateStockHostedService> logger;

        public UpdateStockHostedService(RabbitMqCore mQ,
            HttpClientYouZanYun httpClientYouZanYun,
            ProductInfoBLL productInfoBLL,
            WorkingCenterBLL workingCenterBLL,
            ShopMapBLL shopMapBLL,
            WareHouseDataWarehousBLL wareHouseDataWarehousBLL,
            WareHouseDataAllBLL wareHouseDataAll,
            ILogger<UpdateStockHostedService> logger)
        {
            this.mQ = mQ;
            this.httpClientYouZanYun = httpClientYouZanYun;
            this.productInfoBLL = productInfoBLL;
            this.workingCenterBLL = workingCenterBLL;
            this.shopMapBLL = shopMapBLL;
            this.wareHouseDataWarehousBLL = wareHouseDataWarehousBLL;
            this.wareHouseDataAll = wareHouseDataAll;
            this.logger = logger;

            //V_ProductInfoMap productMap = this.productInfoBLL.QueryVProductInfoMap(98696905, PlatformEnum.YouZanYun);
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        } 
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            Task task = base.StopAsync(cancellationToken);
            Process.GetCurrentProcess().Kill();
            return task;

        }
       
        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        { 
            IModel channel = this.mQ.connection.CreateModel();

            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
            consumer.Received += Consumer_Received;
            channel.BasicQos(0, 0, false);
            string queue = mQ.Update_Stock_Queue;
            channel.BasicConsume(queue: queue, autoAck: false, consumer: consumer);

            await Task.CompletedTask;
        }

        private void Consumer_Received(object sender, BasicDeliverEventArgs e)
        {
            //向推算服务器发消息
            byte[] data = e.Body.ToArray();

            UpdateStock updateStock = JsonSerializer.Deserialize<UpdateStock>(data);
            if (updateStock.Key == "UpdateErp") //处理Erp库存
            {
                //调用Erp接口
            }
            else if (updateStock.Key == "UpdatePlat") //调用第三方平台接口
            {
                //有赞云更新库存  
                foreach (ProductStock product in updateStock.Data)
                {
                    //更新有赞 
                    Update(updateStock.WarehousSN, product);
                }
            }

            //确认,无论是否成功，都确认
            EventingBasicConsumer consumer = (EventingBasicConsumer)sender;
            consumer.Model.BasicAck(e.DeliveryTag, false);

            string message = System.Text.Encoding.UTF8.GetString(e.Body.ToArray());
            string line = $"消费:{message} ";
            //line += $"[RoutingKey]:{e.RoutingKey} ";
            //line += $"[DeliveryTag]:{e.DeliveryTag} ";
            //line += $"[ConsumerTag]:{e.ConsumerTag} ";
            //line += $"[Exchange]:{e.Exchange} ";
            Console.WriteLine(line);
        }

        private void Update(string warehousSN, ProductStock product)
        {
            long ProductSN = product.ProductSN;

            //--------------------1.获取有赞云分店SN
            ShopRelatedEntity shopRelatedEntity = this.workingCenterBLL.QueryShopRelate(warehousSN);
            if (shopRelatedEntity == null || shopRelatedEntity.ShopVSN == 0)
            {
                this.logger.LogError($"ProductSN:{ProductSN} >> 门店:{warehousSN}在Erp中没有映射!");
                return;
            }

            int ShopVSN = shopRelatedEntity.ShopVSN;            //虚拟分店SN 
            ShopMapEntity shopMap = this.shopMapBLL.Get(ShopVSN, PlatformEnum.YouZanYun);
            if (shopMap == null || shopMap.app_poi_code == 0)
            {
                this.logger.LogError($"ProductSN:{ProductSN} 门店:{ShopVSN}在B2C中没有映射!");
                return;
            }

            long node_kdt_id = shopMap.app_poi_code; //有赞分店SN

            //--------------------2.获取有赞云产品SN
            //ProductInfoRelatedEntity productRelate = this.workingCenterBLL.QueryProductInfoRelated(warehousSN, ProductSN);
            //if (productRelate == null || productRelate.ProductVSN == 0)
            //{
            //    this.logger.LogError($"ProductSN:{ProductSN} 在Erp中没有映射!");
            //    return;
            //}
            //long productVSV = productRelate.ProductVSN;
             
            //ProductInfoMapEntity productMap = this.productInfoBLL.QueryMap(productVSV, PlatformEnum.YouZanYun);
            //if (productMap == null || productMap.app_medicine_id == 0)
            //{
            //    this.logger.LogError($"ProductSN:{ProductSN}  虚拟产品SN:{productVSV} 没有配置有赞云平台产品SN!");
            //    return;
            //}

            ////int Qty = GetQty(ShopVSN, warehousSN, productVSV, product.Qty, product.ProductSN);
            //UpdateQtyYzy(node_kdt_id, productMap.app_medicine_id, ProductSN, product.Qty, shopMap.CompanySN);
        }

        ///// <summary>
        ///// 更新
        ///// </summary>
        ///// <param name="warehousSN">分仓编号</param>
        ///// <param name="ProductSN">Erp产品SN</param>
        //private void Update(string warehousSN, long ProductSN)
        //{
        //    //--------------------1.获取有赞云分店SN
        //    ShopRelatedEntity shopRelatedEntity = this.workingCenterBLL.QueryShopRelate(warehousSN);
        //    if (shopRelatedEntity == null || shopRelatedEntity.ShopVSN == 0)
        //    { 
        //        this.logger.LogError($"ProductSN:{ProductSN} >> 门店:{warehousSN}在Erp中没有映射!");
        //        return;
        //    }

        //    int ShopVSN = shopRelatedEntity.ShopVSN;            //虚拟分店SN 
        //    ShopMapEntity shopMap = this.shopMapBLL.Get(ShopVSN, PlatformEnum.YouZanYun);
        //    if (shopMap == null || shopMap.app_poi_code == 0)
        //    {
        //        this.logger.LogError($"ProductSN:{ProductSN} 门店:{ShopVSN}在B2C中没有映射!");
        //        return;
        //    }

        //    long node_kdt_id = shopMap.app_poi_code; //有赞分店SN

        //    //--------------------2.获取有赞云产品SN
        //    ProductInfoRelatedEntity productRelate = this.workingCenterBLL.QueryProductInfoRelated(warehousSN, ProductSN);
        //    if (productRelate == null || productRelate.ProductVSN == 0)
        //    {
        //        this.logger.LogError($"ProductSN:{ProductSN} 在Erp中没有映射!");
        //        return;
        //    }
        //    long productVSV = productRelate.ProductVSN;
             
        //    //V_ProductInfoMap productMap = this.productInfoBLL.QueryVProductInfoMap(productVSV, PlatformEnum.YouZanYun); 
        //    ProductInfoMapEntity productMap = this.productInfoBLL.QueryMap(productVSV, PlatformEnum.YouZanYun);
        //    if (productMap == null || productMap.app_medicine_id == 0)
        //    {
        //        this.logger.LogError($"ProductSN:{ProductSN}  虚拟产品SN:{productVSV} 没有配置有赞云平台产品SN!");
        //        return;
        //    }

        //    int Qty = GetTotalQty(shopRelatedEntity.ShopVSN, productRelate.ProductVSN, ProductSN);  //库存总量

        //    UpdateQtyYzy(node_kdt_id, productMap.app_medicine_id, ProductSN, Qty, shopMap.CompanySN);
        //}

        ///// <summary>
        ///// 虚拟产品SN，在所有分店下的库存
        ///// </summary>
        ///// <param name="ShopVSN"></param>
        ///// <param name="ProductVSN"></param>
        ///// <param name="erpProductSN"></param>
        ///// <returns></returns>
        //private int GetTotalQty(int ShopVSN, long ProductVSN, long erpProductSN)
        //{ 
        //    List < ShopRelatedEntity > shopList = this.workingCenterBLL.QueryShopRelateList(ShopVSN);                           //分店Erp映射
        //    List < ProductInfoRelatedEntity > productList = this.workingCenterBLL.QueryProductInfoRelatedList(ProductVSN);      //产品Erp映射
        //    int Qty = 0;
        //    if (shopList != null && productInfoBLL != null)
        //    { 
        //        foreach (ShopRelatedEntity shopRelate in shopList) //分店
        //        {
        //            //统计erp库存 
        //            ProductInfoRelatedEntity product = productList.Where<ProductInfoRelatedEntity>(ww => ww.WarehousSN == shopRelate.WarehousSN)
        //                                                        .FirstOrDefault(); //erp产品SN

        //            if (product != null && product.ProductSN > 0)
        //            {
        //                try
        //                {
        //                    SqlSugarClient erpClient = DbScoped.CreateSugar(shopRelate.ServerName); //erp操作实例  
        //                    erpClient.ChangeDatabase("YZ_Med_LMSystem");

        //                    //Erp的库存数
        //                    string sql = "select sum(qty) as qty from WM_WareHouseData where qty > 0 and productSN = " + product.ProductSN.ToString();
                        
        //                    int tempQty = (int)erpClient.Ado.GetDecimal(sql); 
        //                    Qty += tempQty;

        //                    //更新分店库存
        //                    WareHouseDataWarehousEntity info = new WareHouseDataWarehousEntity();
        //                    info.ShopVSN = ShopVSN;
        //                    info.WarehousSN = shopRelate.WarehousSN;
        //                    info.ProductVSN = ProductVSN;
        //                    info.Qty = tempQty;
        //                    this.wareHouseDataWarehousBLL.Save(info);
        //                }
        //                catch (Exception ex)
        //                { 
        //                    throw ex;
        //                } 
        //            }
        //        }

        //        //更新总库存
        //        WareHouseDataAllEntity infoAll = new WareHouseDataAllEntity();
        //        infoAll.ShopVSN = ShopVSN;
        //        infoAll.ProductVSN = ProductVSN;
        //        infoAll.Qty = Qty; 
        //        this.wareHouseDataAll.Save(infoAll);
        //    }
        //    else
        //    {
        //        this.logger.LogInformation($"Product:{erpProductSN} erp分店映射没配置,或者erp产品映射没配置");
        //    }
           

        //    //更新总店库存

        //    return Qty;
        //}

        //private int GetQty(int ShopVSN, string warehousSN, long ProductVSN, int Qty, long erpProductSN)
        //{
        //    int qty = this.wareHouseDataWarehousBLL.CalcQty(ShopVSN, warehousSN, ProductVSN, Qty);
        //    return qty;
        //}
         
        private async void UpdateQtyYzy(long node_kdt_id, long app_medicine_id, long ProductSN, int Qty, long CompanySN)
        {
            StockUpdateRequest data = new StockUpdateRequest(); 
            
            data.root_item_id = app_medicine_id;    //商品
            List<ItemUpdateParam> list = new List<ItemUpdateParam>();
            ItemUpdateParam itemUpdateParam = new ItemUpdateParam();
            itemUpdateParam.stock_num = Qty;
            //itemUpdateParam.price = (long)price * 100;
            itemUpdateParam.node_kdt_id = node_kdt_id;  //有赞分店SN
            list.Add(itemUpdateParam);
            data.no_sku_update_open_param_list = list;

            //获取有赞总部SN
            long app_poi_code2 = this.shopMapBLL.GetKdtId(CompanySN);
            this.httpClientYouZanYun.authority_id = app_poi_code2.ToString();
            try
            {
                ItemUpdateResult result = await this.httpClientYouZanYun.BranchUpdateStock(data);
                if (result.success)
                {
                    foreach (ItemUpdateData data1 in result.data)
                    {
                        if (!data1.is_success)
                        {
                            this.logger.LogInformation($"{ProductSN}:{data1.message}");
                        }
                    }

                    this.logger.LogInformation($"ProductSN:{ProductSN}: 更新成功！");
                }
                else
                {
                    this.logger.LogError($"ProductSN:{ ProductSN}:{result.message}-{result.request_id}");
                }
            }
            catch (Exception ex)
            {
                this.logger.LogError($"ProductSN:{ ProductSN}:{ex.Message}");
            }
        }

    }
}
